package server

import (
	"encoding/json"
	"fmt"
	"gitee.com/game_diamond/protocols"
	"sync"
)

const SocketRotateSize = 10

type socket struct {
	Id        int
	Actor     int
	fd        int
	ReadChan  chan string
	WriteChan chan string
	conn      interface{}
}

func (s *socket) Write(msg []byte) error {
	s.WriteChan <- string(msg)
	return nil
}

func (s *socket) ReadLoop() error {
	for {
		select {
		case msg := <-s.ReadChan:
			body := new(protocols.WebSocketBody)
			json.Unmarshal([]byte(msg), body)
			f, err := GetWsAction(s.Actor, body.Action)
			if err != nil {
				//msg error
				s.Write([]byte(fmt.Sprintf("actor %v; action %v ; err %v", s.Actor, body.Action, err)))
				continue
			}
			f(s.Id, body)
		}
	}
	return nil
}

type pool struct {
	Lock    *sync.Mutex
	Sockets map[int]*socket
}

var (
	poolList  = make(map[int]pool)
	poolMutex = new(sync.Mutex)
)

func PoolAddSocket(s *socket) error {
	//取模

	return nil
}

func FindPoolSocket(id int) (*socket, error) {
	//取模

	return nil, nil
}

func WriteSocketMsg(id int, msg []byte) error {
	s, err := FindPoolSocket(id)
	if err != nil {
		return err
	}
	return s.Write(msg)
}
